package cn.jishiyu11.xeqb.activity

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.umeng.analytics.MobclickAgent
import org.json.JSONObject
import java.io.IOException
import java.util.ArrayList
import java.util.HashMap
import cn.jishiyu11.xeqb.R
import cn.jishiyu11.xeqb.base.BaseActivity
import cn.jishiyu11.xeqb.http.http.i.DataCallBack
import cn.jishiyu11.xeqb.http.http.i.httpbase.*
import cn.jishiyu11.xeqb.utils.CameraUtils.UserCenterRealize
import cn.jishiyu11.xeqb.utils.PublicClass.CommissioningTimerUtils
import cn.jishiyu11.xeqb.utils.SharedPreferencesUtils
import cn.jishiyu11.xeqb.view.PublicPhoneDialog
import okhttp3.Request
import cn.jishiyu11.xeqb.utils.AppUtil.getInstance
import cn.jishiyu11.xeqb.utils.showShortToast
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.act_commissioning.*


/**
 * Created by jsy_zj on 2017/6/23.
 * 启动页面
 */
class CommissioningActivity : BaseActivity(), View.OnClickListener, DataCallBack {

    private val userCenterRealize = UserCenterRealize()
    private var getImei = ""
    private var commissioningTimerUtils: CommissioningTimerUtils? = null
    private var boot_url = ""
    private var viewList: MutableList<ImageView>? = null
    private var update_url = ""
    private var isClickImage = false

    @SuppressLint("HandlerLeak")
    private val mHandler = object : Handler() {

        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when (msg.what) {
                100 -> {
                    val phonestrings = msg.obj.toString().split("#".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
                    if (TextUtils.isEmpty(SharedPreferencesUtils.get(this@CommissioningActivity, getString(R.string.username), "").toString())) {
                        if (phonestrings.size > 2) {
                            getImei = phonestrings[1] + "," + phonestrings[2]
                        } else {
                            getImei = phonestrings[1]
                        }
                    } else if (phonestrings[0] == SharedPreferencesUtils.get(this@CommissioningActivity,
                            getString(R.string.username), "").toString()) {
                        getImei = phonestrings[1]
                    } else {
                        getImei = phonestrings[1]
                    }
                }
                101 -> {
                    //                    startActivity( new Intent( CommissioningActivity.this, MainActivity.class ) );
                    val intent = Intent(this@CommissioningActivity, MainActivity::class.java)
                    if (isClickImage) {
                        intent.putExtra("url", boot_url)
                    }
                    startActivity(intent)
                    finish()
                }
            }
        }
    }

    internal var pagerAdapter: PagerAdapter = object : PagerAdapter() {

        override fun isViewFromObject(arg0: View, arg1: Any): Boolean {
            return arg0 === arg1
        }

        override fun getCount(): Int {
            return viewList!!.size
        }

        override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
            container.removeView(viewList!![position])
        }

        override fun getPageTitle(position: Int): CharSequence {
            return "title"
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            container.addView(viewList!![position])
            return viewList!![position]
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.act_commissioning)
        findViewById()
        initView()
    }

    override fun findViewById() {

    }

    override fun initView() {
        if (TextUtils.isEmpty(SharedPreferencesUtils.get(this, getString(R.string.first_time), "").toString())) {
            commissioning_relat!!.visibility = View.GONE
            viewpager_relat!!.visibility = View.VISIBLE
            userCenterRealize.getIMEIPHONE(this, mHandler, 100)
        } else {
            commissioning_relat!!.visibility = View.VISIBLE
            viewpager_relat!!.visibility = View.GONE
            getUPDATE()
        }
        commissioning_button!!.setOnClickListener(this)
        commissioning_image1!!.setOnClickListener(this)
        initData()
        viewpager!!.adapter = pagerAdapter
        indicator!!.setViewPager(viewpager)
        commissioning_loan_button!!.setOnClickListener(this)

        viewpager!!.setOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {

            }

            override fun onPageSelected(position: Int) {
                if (position == 3) {
                    commissioning_loan_button!!.visibility = View.VISIBLE
                } else {
                    commissioning_loan_button!!.visibility = View.GONE
                }
            }

            override fun onPageScrollStateChanged(state: Int) {

            }
        })
    }

    private fun initData() {
        viewList = ArrayList()
//        var imageView = ImageView(this)
//        imageView.setImageResource(R.mipmap.ic_boot_page1)
//        imageView.scaleType = ImageView.ScaleType.FIT_XY
//        viewList!!.add(imageView)
//        imageView = ImageView(this)
//        imageView.setImageResource(R.mipmap.ic_boot_page2)
//        imageView.scaleType = ImageView.ScaleType.FIT_XY
//        viewList!!.add(imageView)
//        imageView = ImageView(this)
//        imageView.setImageResource(R.mipmap.ic_boot_page3)
//        imageView.scaleType = ImageView.ScaleType.FIT_XY
//        viewList!!.add(imageView)
//        imageView = ImageView(this)
//        imageView.setImageResource(R.mipmap.ic_boot_page4)
//        imageView.scaleType = ImageView.ScaleType.FIT_XY
//        viewList!!.add(imageView)
    }

    override fun onResume() {
        super.onResume()
        MobclickAgent.onResume(this)
    }

    override fun onPause() {
        super.onPause()
        MobclickAgent.onPause(this)
    }

    override fun onClick(v: View) {
        when (v.id) {
            R.id.commissioning_button -> {
                commissioningTimerUtils!!.onFinish()
                finish()
            }
            R.id.commissioning_image1 -> {

                isClickImage = true
                commissioningTimerUtils!!.onFinish()
            }

            R.id.commissioning_loan_button -> {
                SharedPreferencesUtils.put(this, getString(R.string.first_time), "1")
                //                getHTTPActivity();
                getUPDATE()
            }
        }//                finish();
        //                finish();
    }

    //    private void getHTTPActivity() {//上传渠道和IMEI码
    //        Map<String, Object> map = new HashMap<>();
    //        map.put( "imei", getImei );
    //        map.put( "mac", getInstance().getMacAddress() );
    //        map.put( "channel", getInstance().getChannel( this, 2 ) );
    ////        OkHttpManager.postAsync( HttpURL.getInstance().ACTIVITY + JSYApplication.PhoneNum, "commissioning_activity", map, this );
    //        OkHttpManager.postAsync( HttpURL.getInstance().ACTIVITY, "commissioning_activity", map, this );
    //    }

    private fun getBOOTAPP() {//获取版本信息
        OkHttpManager.postAsync(BOOTAPP, "boot_app", null, this)
    }

    private fun getUPDATE() {//更新请求
        val map = HashMap<String, Any>()
        map.put("version", getInstance().getVersionName(1, this))
        OkHttpManager.postAsync(UPDATE, "update", map, this)
    }

    override fun requestFailure(request: Request, name: String, e: IOException) {
        when (name) {
            "boot_app" -> this.showShortToast(this.getString(R.string.network_timed))
            "update" -> this.showShortToast(this.getString(R.string.network_timed))
            "getUserLoginAuthorStatus" -> {
            }
        }
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    @Throws(Exception::class)
    override fun requestSuccess(result: String, name: String) {
        var objects:JSONObject? = null
        when (name) {
            "boot_app" -> {
                objects = JSONObject(result)
                if (objects.optString("code") == "0000") {
                    commissioning_button!!.visibility = View.VISIBLE
                    commissioning_image1!!.visibility = View.VISIBLE
                    commissioning_image!!.visibility = View.GONE
                    objects = JSONObject(objects.optString("data"))
                    boot_url = objects.optString("boot_url")
                    var boot_urls = HTTP_URL_PATH + objects.optString("boot_img")
                    Glide.with(this)
                            .load(boot_urls)
                            .listener(object :RequestListener<String,GlideDrawable>{
                                override fun onResourceReady(resource: GlideDrawable?, model: String?, target: Target<GlideDrawable>?, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
                                    return false
                                }

                                override fun onException(e: java.lang.Exception?, model: String?, target: Target<GlideDrawable>?, isFirstResource: Boolean): Boolean {
                                    commissioning_button!!.visibility = View.GONE
                                    commissioning_image1!!.visibility = View.GONE
                                    commissioning_image!!.visibility = View.VISIBLE
                                return false
                                }

                            })
                            .into(commissioning_image1)

                    commissioningTimerUtils = CommissioningTimerUtils(this, mHandler, commissioning_button,
                            (java.lang.Long.parseLong(objects.optString("time")) + 1) * 1000, 1000)
                    commissioningTimerUtils!!.start()
                } else {
                    commissioning_button!!.visibility = View.GONE
                    commissioning_image1!!.visibility = View.GONE
                    commissioning_image!!.visibility = View.VISIBLE
                    startActivity(Intent(this, MainActivity::class.java))
                }
            }
            "update" -> {
                objects = JSONObject(result)
                if (objects.optString("code") == "0001") {
                    commissioning_relat!!.visibility = View.VISIBLE
                    viewpager_relat!!.visibility = View.GONE
                    commissioning_button!!.visibility = View.GONE
                    getBOOTAPP()
                } else if (objects.optString("code") == "0000") {
                    objects = JSONObject(objects.optString("data"))
                    update_url = objects.optString("update_url")
                    val type = objects.optString("type")
                    val content = objects.optString("content")
                    getPhone(content, type)
                }
            }
            "getUserLoginAuthorStatus" -> {

                objects = JSONObject(result)
                val code = objects.getString("state") + ""
                if (!TextUtils.isEmpty(code) && code == "000") {

                }
            }
        }
    }

    private fun getPhone(msg: String, phone: String) {
        val builder = PublicPhoneDialog.Builder(this)
        builder.setTiltleMsg(msg)
        if (phone == "2") {
            builder.setTitle("建议更新")
//            builder.setContentViewCancel("取消") { dialog, which ->
//                getBOOTAPP()
//                dialog.dismiss()
//            }
//        } else {
//            builder.setTitle("强制更新")
//        }
//        builder.setContentViewDetermine("确定") { dialog, which ->
//            userCenterRealize.getUpdata(this@CommissioningActivity, update_url)
//            getBOOTAPP()
//            dialog.dismiss()
//        }
            builder.setContentViewCancel("取消", object : DialogInterface.OnClickListener {
                override fun onClick(dialog: DialogInterface?, which: Int) {
                    getBOOTAPP()
                    dialog?.dismiss()
                }
            })
        }else{
            builder.setTitle("强制更新")
        builder.setContentViewDetermine("确定",object :DialogInterface.OnClickListener{
            override fun onClick(dialog: DialogInterface?, which: Int) {
                getBOOTAPP()
                dialog?.dismiss()
            }
        })}

        builder.create().show()
    }

    companion object {
        private val REQUEST_PERMISSION = 0
    }




}
